package com.lzh.log.filter;

import com.lzh.log.util.MDCTraceUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhehen.lu
 * @date 2025/08/10 09:49
 */
@Component
@Order(-1)
public class WebTraceFilter extends OncePerRequestFilter {
    public WebTraceFilter() {
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String traceId = request.getHeader("x-traceId-header");
            String spanId = request.getHeader("x-spanId-header");
            if (StringUtils.isEmpty(traceId)) {
                MDCTraceUtil.addTraceId();
            } else {
                MDCTraceUtil.putTraceId(traceId, spanId);
            }

            filterChain.doFilter(request, response);
        } finally {
            MDCTraceUtil.removeTraceId();
        }

    }
}
